/*
 * 文件名： MgFragment.java
 * 描    述：MainActivity -- 默认页
 * 时    间：2015-3-25 下午5:47:21
 * 版    本：V1.0
 */

package com.miguo.activity.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.alibaba.sdk.android.util.NetworkUtils;
import com.miguo.activity.MainActivity;
import com.miguo.activity.base.BaseListFragment;
import com.miguo.activity.callback.IFragment;
import com.miguo.activity.callback.IGoods;
import com.miguo.activity.callback.IGoodsScroll;
import com.miguo.activity.callback.listener.GoodsScrollListener;
import com.miguo.adapter.GoodsAdvertAdapter;
import com.miguo.adapter.HomeAdSliderAdapter;
import com.miguo.app.AppConfig;
import com.miguo.app.AppHelper;
import com.miguo.bean.AdvertBean;
import com.miguo.bean.CommentBean;
import com.miguo.bean.GoodsAdvertBean;
import com.miguo.component.AdvertGridView;
import com.miguo.component.CategoryGridView;
import com.miguo.component.HomeHeaderNavView;
import com.miguo.db.AdvertDB;
import com.miguo.framework.component.BaseStatusView;
import com.miguo.framework.request.JsonData;
import com.miguo.framework.utils.Toast;
import com.miguo.http.HttpClient;
import com.miguo.http.Url;
import com.miguo.plugins.Statistics;
import com.miguo.ui.R;
import com.miguo.utils.ConfigInfo;
import com.mrper.data.ApkConstant;
import com.mrper.ext.event.AdverLoadFinishedEvent;
import com.mrper.util.DeviceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.lightsky.infiniteindicator.InfiniteIndicatorLayout;
import cn.lightsky.infiniteindicator.slideview.BaseSliderView;
import cn.lightsky.infiniteindicator.slideview.DefaultSliderView;

public class IndexFragment extends BaseListFragment<GoodsAdvertBean, GoodsAdvertAdapter>
        implements OnClickListener, IGoodsScroll, IGoods<GoodsAdvertBean, GoodsAdvertAdapter>, IFragment {

    private View mHeadLayout;
    private MainActivity mMainActivity;

    private List<AdvertBean> mCategoryGridList;
    private CategoryGridView mCategoryGridLayout;
    private AdvertGridView mAdvertGridLayout;
    private List<AdvertBean> mAdvertGridList;

//    private CirclePageIndicator mIndicator;

    private InfiniteIndicatorLayout mViewPager;
    private List<AdvertBean> mAdvertPagerList;
    private HomeHeaderNavView mHeadNav;
    private HomeAdSliderAdapter mHomeAdAdapter;

    private RelativeLayout mContent;
    private BaseStatusView BaseStatus;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this); //添加时间2016-04-27 10:43
        mMainActivity = (MainActivity) this.getActivity();
        setGoodsCallBack(this);
        findViewById();
        initHeaderView();
        initView();
    }

    @Override
    protected void findViewById() {
        super.findViewById();
        mContent = (RelativeLayout) view.findViewById(R.id.content_view);
        BaseStatus = (BaseStatusView) view.findViewById(R.id.base_status_view);
        BaseStatus.setContentView(mContent);
        BaseStatus.getRefreshView().setOnClickListener(this);
        BaseStatus.getNetworkView().setOnClickListener(this);
    }

    private void initHeaderView() {
        mHeadNav = (HomeHeaderNavView) view.findViewById(R.id.home_head_nav);
        mHeadNav.setActivity(mMainActivity);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        mHeadLayout = inflater.inflate(R.layout.layer_home_head_advertisement, null);

        //修改ViewPager应该的高度值
        View containerView = mHeadLayout.findViewById(R.id.view_pager_rl);
        LinearLayout.LayoutParams containerLayoutParams = (LinearLayout.LayoutParams)containerView.getLayoutParams();
        containerLayoutParams.height = (int)(DeviceUtil.getScreenWidth(mContext) / ApkConstant.INDEX_FRAGMENT_BANNER_PERCENT);
        containerView.setLayoutParams(containerLayoutParams);

        gridView.addHeaderView(mHeadLayout);
        setLoadAdverCategryData();//设置加载广告数据和分类数据
    }

    /**  设置加载广告数据  **/
    private void setLoadAdverCategryData(){
        mAdvertPagerList = AdvertDB.getInstance(mContext).findPosition(2);
        if (mAdvertPagerList !=null && mAdvertPagerList.size() > 0) {
            if(mViewPager == null){
                mViewPager = (InfiniteIndicatorLayout) mHeadLayout.findViewById(R.id.adver_view_pager);
            }
//            if(mIndicator == null){
//                mIndicator = (CirclePageIndicator) mHeadLayout.findViewById(R.id.indicator);
//            }
            if(mHomeAdAdapter == null) {
                mHomeAdAdapter = new HomeAdSliderAdapter(mActivity);
                mHomeAdAdapter.setAdverList(mAdvertPagerList);
                mViewPager.setAdapter(getDefaultSliderItemViews());
                mViewPager.setInfinite(true);
                mViewPager.setStopScrollWhenTouch(true);
                mViewPager.setDirection(InfiniteIndicatorLayout.RIGHT);
                mViewPager.setIndicatorPosition(InfiniteIndicatorLayout.IndicatorPosition.Center_Bottom);
//                mIndicator.setViewPager(mViewPager);
            }else{
                mHomeAdAdapter.setAdverList(mAdvertPagerList);
            }
            mHeadLayout.findViewById(R.id.view_pager_rl).setVisibility(View.VISIBLE);
        } else {
            mHeadLayout.findViewById(R.id.view_pager_rl).setVisibility(View.GONE);
        }
        //网格分类从广告接口加载出来的，所以写在此处
        mCategoryGridList = AdvertDB.getInstance(mContext).findPosition(5);
        if(mCategoryGridLayout == null) {
            mCategoryGridLayout = (CategoryGridView) mHeadLayout
                    .findViewById(R.id.layout_category_grid);
        }
        mCategoryGridLayout.setCategoryList(mCategoryGridList);
        if(mCategoryGridLayout.getActivity() == null) {
            mCategoryGridLayout.setActivity(mMainActivity);
        }
        //网格广告，用于第三个Fragment的分类表现
        if(mAdvertGridLayout == null) {
            mAdvertGridLayout = (AdvertGridView) mHeadLayout
                    .findViewById(R.id.layout_advert_grid);
        }
        mAdvertGridList = AdvertDB.getInstance(mContext).findPosition(4);
        mAdvertGridLayout.setList(mAdvertGridList);
        //通知页面进行数据刷新,这样才能加载出头部部分的内容
        if(mCategoryGridLayout!=null && mCategoryGridLayout.getmCategories()!=null
                && mCategoryGridLayout.getmCategories().size()>0) {
            gridView.notifyDataSetChanged();
        }
    }

    @NonNull
    private List<DefaultSliderView> getDefaultSliderItemViews() {
        List<DefaultSliderView> items = new ArrayList<>();
        for(final AdvertBean item : mAdvertPagerList){
            DefaultSliderView itemCtl = new DefaultSliderView(mContext);
            itemCtl.setScaleType(BaseSliderView.ScaleType.Fit);
            itemCtl.image(item.getHorizontal_pic_url());
            itemCtl.setOnSliderClickListener(new BaseSliderView.OnSliderClickListener() {
                @Override
                public void onSliderClick(BaseSliderView slider) {
                    AppHelper.startActivityByType(mActivity, item);
                }
            });
            items.add(itemCtl);
        }
        return items;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.refresh_rl:
            case R.id.network_error_ll:
                this.onGoodsLoadData();
                break;
        }
        super.onClick(v);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_index, container, false);
        return view;
    }

    @Override
    public void onStartFragment() {
        Statistics.onTrackCustomClick(mContext, AppConfig.STATISTICS.EVENT_NAME_1);
    }

    @Override
    public void onStopFragment() {
    }

    @Override
    public void onResume() {
        super.onResume();
        if(mViewPager != null) mViewPager.startAutoScroll();
    }

    @Override
    public void onPause() {
        if(mViewPager != null) mViewPager.stopAutoScroll();
        super.onPause();
    }

    @Override
    public void onScrollIdle() {
        imageLoader.resume();
    }

    @Override
    public void onScrollFling() {
        if (pauseOnFling) {
            imageLoader.pause();
        }
    }

    @Override
    public void onScrollTouchScroll() {
        if (pauseOnScroll) {
            imageLoader.pause();
        }
    }

    @Override
    public void onScrollTopPositiont() {
        // 判断滚动到顶部
        if (mToTopBtn.getVisibility() == View.VISIBLE) {
            mToTopBtn.setVisibility(View.GONE);
            mToTopBtn.startAnimation(mTopDownAnima);
        }
    }

    @Override
    public void onScrollFirstLastPosition() {
        // 第一次滚动至底部
        if (mToTopBtn.getVisibility() == View.GONE) {
            mToTopBtn.setVisibility(View.VISIBLE);
            mToTopBtn.startAnimation(mTopUpAnima);
        }
    }

    @Override
    public void onScrollLastPosition() {
        // 判断滚动到底部
        if (mToTopBtn.getVisibility() == View.GONE) {
            mToTopBtn.setVisibility(View.VISIBLE);
            mToTopBtn.startAnimation(mTopUpAnima);
        }
        if (pageSize >= page + 1) {
            page++;
            isRefresh = false;
            this.onGoodsLoadData();
        } else {
            Toast.show(mContext, "已经到底了!");
            pullToRefresh.onRefreshComplete();
        }
    }

    @Override
    public GoodsAdvertAdapter onGoodsLoadAdapter() {
        return new GoodsAdvertAdapter(mActivity);
    }

    @Override
    public List<GoodsAdvertBean> onGoodsDealList(JsonData data) {
        return CommentBean.GoodsAdvertData(data);
    }

    @Override
    public void onGoodsLoadData() {
        if(!ConfigInfo.IsRequestConfigData && page == 1)//如果没有请求到配置及分类信息
            ConfigInfo.startConfigRequest(mContext);//处理App配置
        //正常数据请求
        Map<String, String> param = new HashMap<>();
        param.put("page", String.valueOf(page));
        param.put("show_type",String.valueOf(0)); //0-全部 1-当日最新
        HttpClient.post(Url.toRoute(Url.Item.List, 1), param, AjaxCallBack);
    }

    @Override
    public GoodsScrollListener onGoodsScroll() {
        return new GoodsScrollListener(this);
    }

    @Override
    public void onGoodsRefresh() {
        BaseStatus.setRefreshVisibility(View.VISIBLE);
    }

    @Override
    public void onGoodsFinish() {
        BaseStatus.setRefreshVisibility(View.GONE);
    }

    @Override
    public void onGoodsError() {
        BaseStatus.setRefreshVisibility(View.VISIBLE);
    }

    @Override
    public void onGoodsFail() {
        BaseStatus.setRefreshVisibility(View.VISIBLE);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this); //添加时间2016-04-27 10:43
        super.onDestroy();
    }

    //添加时间2016-04-27 10:43
    @Subscribe
    public void onAdverLoadFinishedEvent(AdverLoadFinishedEvent event){
        if(NetworkUtils.isNetworkAvaiable(mContext)) {
            setLoadAdverCategryData();//设置加载广告数据
            onGoodsLoadData();//请求商品数据
        }
    }

//    @Subscribe
//    public void onCategoryLoadFinishedEvent(CategoryLoadFinishedEvent event){
////        setLoadCategoryData();//设置加载类型数据
//    }

}